﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class SearchI18NText
{
    private static readonly List<string> StrList = new();

    [MenuItem("Assets/Mini Tools/Prefab/遍历多语言文本", false, 302)]
    static void Main()
    {
        StrList.Clear();

        var guids = AssetDatabase.FindAssets("t:Prefab", new[] { "Assets" });
        for (var i = 0; i < guids.Length; i++)
        {
            var guid = guids[i];
            var path = AssetDatabase.GUIDToAssetPath(guid);
            ProcessPerPrefab(path, i, guids.Length);
        }

        EditorUtility.ClearProgressBar();

        var desktop_path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        File.WriteAllLines(Path.Combine(desktop_path, "i18n.txt"), StrList, Encoding.Default);

        Debug.Log("Complete");
    }

    private static void ProcessPerPrefab(string path, int curr, int total)
    {
        UnityEngine.Object o = AssetDatabase.LoadMainAssetAtPath(path);
        GameObject go = null;
        try
        {
            StrList.Add(path);
            int cnt = StrList.Count;
            go = (GameObject)PrefabUtility.InstantiatePrefab(o);
            var r = ProcessPerGameObject(go);
            PrefabUtility.SavePrefabAsset(go);
            if (r)
            {
                Debug.Log($"Save {path}");
                PrefabUtility.SaveAsPrefabAsset(go, path);
            }
            if (StrList.Count == cnt)
            {
                StrList.RemoveAt(StrList.Count - 1);
            }

            EditorUtility.DisplayProgressBar("Progress", $"total_cnt={total}; cur_cnt={curr}", curr / total);
        }
        catch (Exception e)
        {
            Debug.LogError($"e={e} path={path}");
            EditorUtility.ClearProgressBar();
        }
        finally
        {
            if (go != null)
            {
                GameObject.DestroyImmediate(go);
            }
        }
    }

    private static bool ProcessPerGameObject(GameObject go)
    {
        var text = go.GetComponent<Text>();
        var result = false;
        if (text != null)
        {
            if (Regex.IsMatch(text.text, @"[\u4e00-\u9fa5]{1,}"))
            {
                var str = Regex.Replace(text.text, @"\s", "");
                StrList.Add($"go.name = {go.name}; txt={str}");
                if (go.GetComponent<LanguageText>() == null)
                {
                    go.AddComponent<LanguageText>();
                    result = true;
                }
            }
        }

        foreach (Transform child in go.transform)
        {
            var r = ProcessPerGameObject(child.gameObject);
            if (result == false)
            {
                result = r;
            }
        }
        return result;
    }
}
